var timer
$(function () {
    //
    //----
    /**
     * Init
     *
     *
     * |--
     * |   `--
     * |   `--
     * |       `--
     * |           `--
     * |           `--
     * |               `--
     * |           `--
     * |--
     * |--
     */
    var ad = appData();

    var webScokets = new WebSocket(appApi("SOCKET_URL"));

    DomNameStart()

    function DomNameStart() {



        //侧面添加class索引加载
        if (!$.getUrlParam("id")) {
            $('.sys-sidebar ul li').eq(0).find('ul li ').eq(0).addClass('active')

            var name = $('.sys-sidebar').find('li .active a').text()

            //			if(==0){
            //				pageType= 'HbaseFWRZ'
            //			}
            $("#TopName").text(name) //替换头部日志名称
        }

        $("#lookM").on('click', function () {

            //$("#sys-main").empty().load('views/safeApp/dataRegulation/riskEvent.html')
            var url = window.location.href.split('?')[0] + '?page=views/safeApp/dataRegulation/riskEvent';

            window.open(url)
        })

    }

    loadDom()
    if (timer) {

        clearInterval(timer)
    }

    timer = setInterval(function () {

        if ($('.sys-sidebar').find('li .active a').text() == '资源状态') {
            loadTop()

        } else {
            clearInterval(timer)
        }

    }, 60000)

    function loadDom() {
        //加载顶部数据
        loadTop()

        ad.selectList("SOURCE_DATA_LIST", {}, function (data) {
            $("#listTab").empty()
            for (var i = 0; i < data.length; i++) {
                $("#listTab").append(
                    `<div class="col-6">
			            <ul data-id="${data[i].id}" data-type="${data[i].type}">
			              <li>
			              ${data[i].libraryName} <a href="javascript:void(0)" skipData="${data[i].libraryName}" title="管理"><i class="icon-setting"></i>
			              </a><a href="javascript:void(0)" class="safetyindex" title="安全指数"><strong>${data[i].deNum}</strong></a>
			              </li>
			              <li>
			                <span class="col-left">流量情况
			                 <a href="javascript:void(0)" skipStatus="${data[i].id}"  title="查看"><i class="icon-eye-o"></i></a>
			                </span>
			                <span class="col-right">
			                <label class="${data[i].flow[0].state}!=-1?label  fc-danger : label  fc-success">读:${data[i].flow[0].num}<i class="icon-order-desc"></i></label>
                 			<label class="${data[i].flow[1].state}!=-1 ?label  fc-success : label  fc-success">写:${data[i].flow[1].num}<i class="icon-order-asc"></i></label>
			                </span>
			              </li>
			              <li>
			                <span class="col-left">风险事件
			                <a href="javascript:void(0)"  title="查看" skipRisk="${data[i].libraryName}"><i class="icon-eye-o"></i></a></span>
			                <span class="col-right">
			                <label class="label label-danger risk" data-risk="4">高：${data[i].rank[0]}</label>
			                <label class="label label-warning risk" data-risk="3">中：${data[i].rank[1]}</label>
			                <label class="label label-primary risk" data-risk="2">低：${data[i].rank[2]}</label>
			                </span>
			              </li>
			              <li>
			                <span class="col-left">活跃客户端IP数</span>
			                <span class="col-right" style="margin-left:115px"><a href="javascript:void(0)" class="viewIps" data-type="${data[i].type}" data-id="${data[i].id}" >${data[i].ip}</a></span>
			              </li>
			              
			            </ul>
			          </div>`
                )
                //				<li>
                //			                <span class="col-left">节点情况</span>
                //			                <span class="col-right"><label class="label">内网IP：${data[i].ips[0]}</label>
                //			                <label class="label">外网IP：${data[i].ips[1]}</label></span>
                //			              </li>
            }
            //runPage([$("a[skipRisk]"),$("a[skipData]"),$("a[skipStatus]")])
            runPage([$(".col-right .risk"), $("a[skipData]"), $("a[skipStatus]")])
        })

        ad.selectList("SOURCE_DATA_TAB", {}, function (data) {
            loadR(data, true)
        })
    }

    function loadR(data, isOnly) {

        if (isOnly) {
            $("#rightTab").empty()
        }

        for (var i = 0; i < data.length; i++) {

            function aString() {
                var ranks = ['高', '中', '低']
                var str = ''
                if (ranks.indexOf(data[i].rank) == 0) {
                    str = `<label class="badge badge-danger">${data[i].rank}</label>`
                } else if (ranks.indexOf(data[i].rank) == 1) {
                    str = `<label class="badge badge-warning">${data[i].rank}</label>`

                } else {
                    str = `<label class="badge ">${data[i].rank}</label>`

                }
                return str
            }

            $("#rightTab").append(
                `<li>
            	<span>${data[i].time}</span>
            	<span>违规时间段访问规则${aString()}</span>
            	<span><em class="${data[i].type == "数据删除" ? "fc-danger" : ''}">${data[i].type}：</em>hbase1</span>
            </li>`
            )

        }
        $(".scrollbar").mCustomScrollbar({
            autoHideScrollbar: true,
            advanced: {
                autoExpandHorizontalScroll: true
            }
        });
        if ($("#rightTab li").lenght >= 50) {
            $("#rightTab li").eq(49).remove()
        }
    }

    function loadTop() {
        ad.selectList("SOURCE_DATA_NUM", {}, function (data) {
            $("#sourceNum").text(data.sourceNum)
            $("#dataNum1").html("流出 ： " + data.dataNum[0] + '<br>' + "流入 ： " + data.dataNum[1])
            //$("#dataNum2").text("写入 ： "+data.dataNum[1])
            $("#riskNum").text(data.riskNum)
            //$("#riskTi").text(data.riskTi)
            //	$(".circle li").css({"padding":"12px 10px"})
            loadChart(data.value)

        })
    }

    webScokets.onmessage = function (msg) {


        var data = JSON.parse(msg.data)

        function convertString(obj) {
            var ranks = ['高', '中', '低']
            var str = ''
            if (ranks.indexOf(obj.rank) == 0) {
                str = `<label class="badge badge-danger">${obj.rank}</label>`
            } else if (ranks.indexOf(obj.rank) == 1) {
                str = `<label class="badge badge-warning">${obj.rank}</label>`
            } else {
                str = `<label class="badge ">${obj.rank}</label>`
            }
            return str
        }

        if (data.socketType == 'SOCKET_DATA_MANAGER_ZYGL_TYPE') {
            //loadR(datas,false)
            var obj = data.data;
            $("#rightTab").prepend(
                `<li>
				            	<span>${obj.time}</span>
				            	<span>违规时间段访问规则${convertString(obj)}</span>
				            	<span>客户端：${obj.ip}</span>
				            	<span><em class="${obj.type == "数据删除" ? "fc-danger" : ''}">${obj.type}：</em>hbase1</span>
				            </li>`
            )
        }

    };

    function loadChart(val) {
        var option21 = {
            title: {
                text: '安全指数',
                "x": "center",
                top: '84%',
                textStyle: {
                    fontSize: 20
                }

            },
            series: [{
                name: '风险概况',
                type: 'gauge',
                radius: '100%',
                axisLine: {
                    lineStyle: {
                        width: 6,
                        color: [[0.2, '#d92738'], [0.4, '#fb8600'], [0.6, '#fb8600'], [0.8, '#fb8600'], [1, '#7ab30d']]
                    }
                },
                splitLine: {           // 分隔线
                    length: 10,         // 属性length控制线长
                    lineStyle: {       // 属性lineStyle（详见lineStyle）控制线条样式
                        color: 'auto'
                    }
                },
                center: ['50%', '50%'], // 默认全局居中

                data: [{
                    value: val
                }]
            }]
        };
        var myChart1 = echarts.init(document.getElementById('chart21'));
        myChart1.setOption(option21, true);

    }


    function runPage(ids) {
        ids[0].on('click', function () {
            var riskT = this.dataset.risk
            var val = $(this).parents('ul').attr('data-id')

            if (localStorage.getItem('risk')) {
                localStorage.removeItem('risk')
            }
            //var risk = sessionStorage(parma[0])
            localStorage.setItem("risk", val)
            //$("#sys-main").empty().load('views/safeApp/dataRegulation/riskEvent.html')
            var url = window.location.href.split('?')[0] + '?page=views/safeApp/dataRegulation/riskEvent';

            window.open(url + '&id=' + val + '&risk=' + riskT)
        })
        ids[1].on('click', function () {

            var url = window.location.href.split('?')[0] + '?page=views/safeApp/dataRegulation/dataResourceAllocation';

            window.open(url)

        })
        ids[2].on('click', function () {
            var val = $(this).parents('ul').find("a[skipStatus]").attr('skipStatus'),
                type = $(this).parents('ul').attr('data-type'),
                url = ''

            if (type == 'FTPCJRZ') {
                url = window.location.href.split('?')[0] + '?page=views/safeApp/trafficAnalysis/FTPflow';
            } else {
                url = window.location.href.split('?')[0] + '?page=views/safeApp/trafficAnalysis/trafficView';
            }


            window.open(url + '&id=' + val)
//			if(localStorage.getItem('risk')){
//				localStorage.removeItem('risk')
//			}
//			//var risk = sessionStorage(parma[0])
//			localStorage.setItem("risk",val)
//			
//			$("#sys-main").empty().load('views/safeApp/trafficAnalysis/trafficView.html')

        })


        $('.viewIps').on('click', function () {

            var type = this.dataset.type
            var id = this.dataset.id

            $("#info").show()
            showTable(true, 1, 'KMGA_RESOURCES_IPPAGE', 'ipPage','ipPageList','scripts/app/safe/trafficAnalysis/ipPageInfo.tmpl',id,type)
        })

    }
    var paramsT={}

    //分页信息.0
    function showTable(dontRenderPager, page, url, domId,listId,tmp,id,type) {
        paramsT.page = page
        paramsT.pageSize = 15
        paramsT.id=id
        paramsT.type=type
        ad.selectList(url, paramsT, function (data) {
            $("#" + domId).empty();
            if (data.content.length === 0) {
                $("#" + domId).append("<tr><td colspan='4'  class='colspanCss'><h1>暂无数据</h1></td></tr>");
                $("#pageList").empty();
                return;
            }
            if (data.content <= appApi("PAGE_SIZE")) {
                $("#pageList").empty();
                return;
            }
            $.get(tmp, function (tmpl) {
                $("#" + domId).empty();
                $.tmpl(tmpl, data).appendTo("#" + domId);

                //table 排序插件
                $('table').tablesort().data('tablesort');
                if (dontRenderPager) {
                    renderPager(data.totalRecord,null,listId,domId,tmp,url,id,type);
                }
            })

        });
    }

    function renderPager(totalRecord, nowPage,listId,domId,tmp,url,id,type) {
        $("#"+listId).pagination(totalRecord, 15, {
            callback: function (page_id, jq) {
                pageNumNow = page_id + 1;
                showTable(false, pageNumNow, url, domId,listId,tmp,id,type);
            }
        }, nowPage);
    }

    $(".dialog .close,#cancel").on("click",function(){
        $(".dialog").hide();
    })

})
